Page({
  data: {
    isEdit: false,
    activity: {
      _id: '',
      title: '',
      description: '',
      coverUrl: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
      voteLimit: 3
    },
    candidates: [] as any[],
    loading: false
  },

  onLoad(options: any) {
    // 判断是创建还是编辑
    if (options.id) {
      this.setData({
        isEdit: true,
        'activity._id': options.id
      })
      
      // 获取活动详情
      this.getActivityDetail(options.id)
    }
  },

  onShow() {
    // 从候选人编辑页面返回时，重新处理候选人的短描述
    const candidates = this.data.candidates.map(candidate => ({
      ...candidate,
      shortDescription: candidate.description ? 
        (candidate.description.length > 10 ? 
          candidate.description.substring(0, 10) + '...' : 
          candidate.description) : '暂无描述'
    }))
    
    this.setData({
      candidates
    })
  },

  // 获取活动详情
  async getActivityDetail(activityId: string) {
    wx.showLoading({
      title: '加载中...'
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'activityManager',
        data: {
          action: 'getDetail',
          activityId: activityId
        }
      })

      const response = result.result as any
      if (response && response.success) {
        const { activity, candidates } = response.data
        
        // 格式化时间数据
        const formattedActivity = {
          ...activity,
          startDate: activity.startTime ? this.formatDateForInput(new Date(activity.startTime)) : '',
          startTime: activity.startTime ? this.formatTimeForInput(new Date(activity.startTime)) : '',
          endDate: activity.endTime ? this.formatDateForInput(new Date(activity.endTime)) : '',
          endTime: activity.endTime ? this.formatTimeForInput(new Date(activity.endTime)) : ''
        }
        
        // 处理选手数据，添加短描述
        const processedCandidates = (candidates || []).map((candidate: any) => ({
          ...candidate,
          shortDescription: candidate.description ? 
            (candidate.description.length > 10 ? 
              candidate.description.substring(0, 10) + '...' : 
              candidate.description) : '暂无描述'
        }))
        
        this.setData({
          activity: formattedActivity,
          candidates: processedCandidates
        })
        
        console.log('获取活动详情成功:', formattedActivity)
      } else {
        wx.showToast({
          title: response?.message || '获取活动详情失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('获取活动详情失败:', error)
      wx.showToast({
        title: '获取活动详情失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 格式化日期为输入框格式 (YYYY-MM-DD)
  formatDateForInput(date: Date): string {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 格式化时间为输入框格式 (HH:MM)
  formatTimeForInput(date: Date): string {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${hours}:${minutes}`
  },

  // 输入活动标题
  inputTitle(e: any) {
    this.setData({
      'activity.title': e.detail.value
    })
  },

  // 输入活动描述
  inputDescription(e: any) {
    this.setData({
      'activity.description': e.detail.value
    })
  },

  // 选择活动封面
  chooseCover() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 上传图片到云存储
        this.uploadCoverToCloud(tempFilePath)
      }
    })
  },

  // 上传封面到云存储
  async uploadCoverToCloud(tempFilePath: string) {
    wx.showLoading({
      title: '上传中...'
    })
    
    try {
      // 生成文件名
      const timestamp = Date.now()
      const fileExtension = tempFilePath.split('.').pop() || 'jpg'
      const fileName = `activities/covers/${timestamp}.${fileExtension}`
      
      // 上传到云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: fileName,
        filePath: tempFilePath
      })
      
      if (uploadResult.fileID) {
        // 更新封面URL
        this.setData({
          'activity.coverUrl': uploadResult.fileID
        })
        
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        })
        
        console.log('封面上传成功:', uploadResult.fileID)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('上传封面失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 选择开始日期
  startDateChange(e: any) {
    this.setData({
      'activity.startDate': e.detail.value
    })
  },

  // 选择开始时间
  startTimeChange(e: any) {
    this.setData({
      'activity.startTime': e.detail.value
    })
  },

  // 选择结束日期
  endDateChange(e: any) {
    this.setData({
      'activity.endDate': e.detail.value
    })
  },

  // 选择结束时间
  endTimeChange(e: any) {
    this.setData({
      'activity.endTime': e.detail.value
    })
  },

  // 输入投票上限
  inputVoteLimit(e: any) {
    const value = parseInt(e.detail.value)
    this.setData({
      'activity.voteLimit': isNaN(value) ? 1 : Math.max(1, value)
    })
  },

  // 添加选手
  addCandidate() {
    const { activity } = this.data
    
    // 构建跳转URL，传递活动ID（如果是编辑模式）
    let url = '/pages/admin/candidate/edit/index'
    if (activity._id) {
      url += `?activityId=${activity._id}`
    }
    
    wx.navigateTo({
      url: url
    })
  },

  // 添加候选人回调方法（从候选人编辑页面返回时调用）
  addCandidateCallback(candidateData: any) {
    // 为新添加的候选人处理短描述
    const processedCandidate = {
      ...candidateData,
      shortDescription: candidateData.description ? 
        (candidateData.description.length > 10 ? 
          candidateData.description.substring(0, 10) + '...' : 
          candidateData.description) : '暂无描述'
    }
    
    const candidates = [...this.data.candidates, processedCandidate]
    this.setData({
      candidates: candidates
    })
    
    wx.showToast({
      title: '选手添加成功',
      icon: 'success'
    })
    
    console.log('选手添加成功:', processedCandidate)
  },

  // 编辑选手
  editCandidate(e: any) {
    const candidateId = e.currentTarget.dataset.id
    const { activity } = this.data
    
    wx.navigateTo({
      url: `/pages/admin/candidate/edit/index?id=${candidateId}&activityId=${activity._id}`
    })
  },

  // 删除选手
  async deleteCandidate(e: any) {
    const candidateId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个选手吗？删除后数据将无法恢复。',
      success: async (res) => {
        if (res.confirm) {
          // 找到要删除的候选人
          const candidate = this.data.candidates.find(item => item._id === candidateId)
          
          if (!candidate) {
            wx.showToast({
              title: '候选人不存在',
              icon: 'error'
            })
            return
          }
          
          // 如果是临时候选人，直接从本地删除
          if (candidate.isTemp || !candidate._id || typeof candidate._id === 'string' && candidate._id.length < 20) {
            const candidates = this.data.candidates.filter(item => item._id !== candidateId)
            
            this.setData({
              candidates
            })
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
            
            console.log('临时选手删除成功:', candidateId)
            return
          }
          
          // 如果是已保存的候选人，调用云函数删除
          try {
            wx.showLoading({
              title: '删除中...'
            })
            
            // 调用后端API删除选手
            const result = await wx.cloud.callFunction({
              name: 'candidateManager',
              data: {
                action: 'delete',
                candidateId: candidateId,
                forceDelete: false // 使用软删除
              }
            })
            
            wx.hideLoading()
            
            const response = result.result as any
            if (response && response.success) {
              // 从本地数组中移除选手
              const candidates = this.data.candidates.filter(item => item._id !== candidateId)
              
              this.setData({
                candidates
              })
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              
              console.log('选手删除成功:', candidateId)
            } else {
              wx.showToast({
                title: response?.message || '删除失败',
                icon: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('删除选手失败:', error)
            wx.hideLoading()
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'error',
              duration: 2000
            })
          }
        }
      }
    })
  },

  // 保存草稿
  async saveDraft() {
    const { activity, isEdit } = this.data
    
    // 检查必填项
    if (!activity.title.trim()) {
      wx.showToast({
        title: '请输入活动名称',
        icon: 'none'
      })
      return
    }
    
    await this.saveActivity('draft')
  },

  // 发布活动
  async publishActivity() {
    const { activity, candidates } = this.data
    
    // 检查必填项
    if (!activity.title.trim()) {
      wx.showToast({
        title: '请输入活动名称',
        icon: 'none'
      })
      return
    }
    
    if (!activity.startDate || !activity.startTime) {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none'
      })
      return
    }
    
    if (!activity.endDate || !activity.endTime) {
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none'
      })
      return
    }
    
    // 验证时间逻辑
    const startDateTime = new Date(`${activity.startDate} ${activity.startTime}`)
    const endDateTime = new Date(`${activity.endDate} ${activity.endTime}`)
    
    if (startDateTime >= endDateTime) {
      wx.showToast({
        title: '结束时间必须晚于开始时间',
        icon: 'none'
      })
      return
    }
    
    if (candidates.length === 0) {
      wx.showToast({
        title: '请添加至少一个选手',
        icon: 'none'
      })
      return
    }
    
    await this.saveActivity('ongoing')
  },

  // 保存活动
  async saveActivity(status: string) {
    const { activity, isEdit, candidates } = this.data
    
    wx.showLoading({
      title: isEdit ? '保存中...' : '创建中...'
    })
    
    try {
      // 构建活动数据
      const activityData: any = {
        title: activity.title.trim(),
        description: activity.description.trim(),
        coverUrl: activity.coverUrl,
        voteLimit: activity.voteLimit,
        status: status
      }
      
      // 如果设置了时间，添加时间字段
      if (activity.startDate && activity.startTime) {
        activityData.startTime = `${activity.startDate} ${activity.startTime}:00`
      }
      
      if (activity.endDate && activity.endTime) {
        activityData.endTime = `${activity.endDate} ${activity.endTime}:00`
      }
      
      let result
      
      if (isEdit) {
        // 更新活动
        result = await wx.cloud.callFunction({
          name: 'activityManager',
          data: {
            action: 'update',
            activityId: activity._id,
            activityData: activityData
          }
        })
      } else {
        // 创建活动
        result = await wx.cloud.callFunction({
          name: 'activityManager',
          data: {
            action: 'create',
            activityData: activityData
          }
        })
      }

      const response = result.result as any
      if (response && response.success) {
        // 获取活动ID（新建活动时从返回结果获取，编辑活动时使用原有ID）
        const activityId = isEdit ? activity._id : response.data.activityId
        
        // 如果有临时候选人数据，需要保存到数据库
        if (!isEdit && candidates.length > 0) {
          console.log('保存候选人数据到数据库:', candidates.length, '个候选人')
          
          // 筛选出临时候选人（没有数据库ID的）
          const tempCandidates = candidates.filter(candidate => candidate.isTemp || !candidate._id)
          
          if (tempCandidates.length > 0) {
            // 批量保存候选人
            for (const candidate of tempCandidates) {
              try {
                const candidateData = {
                  name: candidate.name,
                  description: candidate.description,
                  images: candidate.images || [],
                  videoUrl: candidate.videoUrl || '',
                  videoPoster: candidate.videoPoster || '',
                  extraInfo: candidate.extraInfo || '',
                  activityId: activityId
                }
                
                const candidateResult = await wx.cloud.callFunction({
                  name: 'candidateManager',
                  data: {
                    action: 'create',
                    candidateData: candidateData
                  }
                })
                
                const candidateResponse = candidateResult.result as any
                if (candidateResponse && candidateResponse.success) {
                  console.log('候选人保存成功:', candidate.name)
                } else {
                  console.error('候选人保存失败:', candidate.name, candidateResponse?.message)
                }
              } catch (error) {
                console.error('保存候选人时出错:', candidate.name, error)
              }
            }
          }
        }
        
        wx.showToast({
          title: isEdit ? '保存成功' : '创建成功',
          icon: 'success',
          success: () => {
            setTimeout(() => {
              wx.navigateBack()
            }, 1500)
          }
        })
        
        console.log('活动保存成功:', response.data)
      } else {
        wx.showToast({
          title: response?.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存活动失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  }
}) 